//
// Created by fanghr on 17-12-27.
//

#include "../include.h"
#include "../socket/test_socket.h"

void read_buf(boost::asio::ip::tcp::socket &s, boost::asio::streambuf &buf) {
    uint32_t size = 0;
    boost::asio::read(s, boost::asio::buffer(&size, sizeof(uint32_t)));// 先读取发送来服务端的缓冲区的大小
    boost::asio::read(s, buf, boost::asio::transfer_exactly(size)); // 读取缓冲区中的内容
}

void write_buf(boost::asio::ip::tcp::socket &s, boost::asio::streambuf &buf) {
    uint32_t size = buf.size(); // 要发送的缓冲区大小
    boost::asio::write(s, boost::asio::buffer(&size, sizeof(uint32_t))); // 先发送缓冲区的大小
    boost::asio::write(s, buf, boost::asio::transfer_exactly(size)); // 再发送指定的message_t的大小
}

int main(int argc, char *argv[]) {
    try {
        boost::asio::io_service io_service;
        boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 7000);

        boost::asio::ip::tcp::socket s(io_service);
        boost::asio::connect(s, &ep);
        while (1) {
            message_t message;
            std::cout << "Enter a number:";
            std::cin >> message.num;
            std::cout << "Enter a message:";
            std::cin >> message.str;

            boost::asio::streambuf buf1;
            boost::archive::binary_oarchive oa(buf1);
            oa << message;
            write_buf(s, buf1);
        }
    }
    catch (std::exception &e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }
    return 0;
}